﻿var client;

function getExtensionFileName(name) {
    //文件扩展名的正则表达式
    var patternFileExtension = /\.([0-9a-z]+)(?:[\?#]|$)/i;
    //获得文件扩展名
    return name.match(patternFileExtension);
}

function loadOssConfig(folder, ext, func) {
    $.post("/Upload/GetSTSToken", { Folder: folder, Ext: ext }, function (res) {
        if (res.isSuccess) {
            let ossConfig = {
                secure: true, //*这句话很重要！！！！！！！！！
                region: res.data.regionId,
                accessKeyId: res.data.accessKeyId,
                accessKeySecret: res.data.accessKeySecret,
                stsToken: res.data.securityToken, //加上这一行，问题解决。
                bucket: res.data.bucketName
            };
            client = new OSS(ossConfig);
            func(res.data.fileName);
        }
        else {
            layer.msg(d.msg, { icon: 2 });
        }
    })
}

function putObject(data, folder, ext, func) {
    var loading = layer.load(2);
    try {
        const options = {
            // 获取分片上传进度、断点和返回值。
            progress: (p, cpt, res) => {
            },
            // 设置并发上传的分片数量。
            partSize: 1024 * 1024,//设置分片大小
            timeout: 60000 * 3,//设置超时时间
        };
        this.loadOssConfig(folder, ext, function (fileKey) {
            client.multipartUpload(
                fileKey,
                data,
                options
            ).then(result => {
                console.log(result);
                layer.close(loading);
                result.url = result.url ? result.url : 'https://' + result.bucket + '.oss-cn-shanghai.aliyuncs.com' + result.name;
                func(result);
            }).catch(err => {
                layer.close(loading);
                console.log(err)
            })
            //client.put(
            //    fileKey,
            //    data
            //).then(result => {
            //    console.log(result);
            //    layer.close(loading);
            //    func(result);
            //}).catch(err => {
            //    layer.close(loading);
            //    console.log(err)
            //})

        });
    } catch (e) {
        console.log(e);
    }
}